
<template>
  <view class="live-container">
    <!-- 直播视频区域 -->
    <view class="live-video">
      <!-- 模拟直播视频 -->
      <!-- <video id="videoContainer" class="live-player video-overlay" ></video> -->
      <view id="videoContainer" class="live-player video-overlay" ></view>
    </view>

    <!-- 顶部主播信息 -->
    <view class="live-header">
      <view class="host-info">
        <view class="host-avatar">
          <image src="/static/img/logo.jpg" mode="aspectFill"></image>
        </view>
        <view class="host-details">
          <view class="host-name">@青联直播</view>
          <view class="live-status">
            <view class="live-indicator"></view>
            直播中 · 2.3万人观看
          </view>
        </view>
      </view>
      <view class="header-actions">
              <!-- 修改退出直播间按钮，添加点击事件 -->
              <button class="follow-btn" @click="exitLiveRoom">退出直播间</button>
              <button class="menu-btn" @click="toggleDrawer">
                <text class="fas fa-bars"></text>
              </button>
            </view>
    </view>

    <!-- 弹幕聊天区域 -->
    <view class="chat-panel">
      <!-- 使用 DanmuChat 组件替换原有的弹幕聊天区域 -->
      <DanmuChat 
        :subscribeTopic="subscribeTopic"
        :sendTopic="sendTopic"
        :boxWidth="boxWidth"
        :boxHeight="boxHeight"
        :boxBackgroundColor="boxBackgroundColor"
        :massage="massage"
      />
    </view>

    <!-- 点赞动画 -->
    <view class="like-animations">
      <view 
        v-for="(like, index) in activeLikes" 
        :key="index"
        class="like-animation"
        :style="like.style"
      >
        <text class="fas fa-heart"></text>
      </view>
    </view>

    <!-- 抽屉 -->
    <view class="drawer" :class="{ 'drawer-open': isDrawerOpen }">
      <!-- 抽屉内容容器，用于包裹所有抽屉内容 -->
      <view class="drawer-content">
        <!-- 抽屉头部 -->
        <view class="drawer-header">
          <view class="drawer-title">直播详情</view>
        </view>
        
        <!-- 抽屉主体内容 -->
        <view class="drawer-body"> 
          <!-- 直接引入 TopTimerAndCountdown 组件 -->
          <TopTimerAndCountdown
            :timer="timer"
            :countdown="countdown"
            :isVotingEnded="isVotingEnded"
            @countdownEnded="handleCountdownEnded"
            @countdownRestart="handleCountdownRestart"
            ref="topTimerAndCountdown"
          />
          <view class="search-and-stats">
            <view class="stats">
              <view class="stat-item">
                <view class="stat-value">{{ totalVotes }}</view>
                <view class="stat-label">总票数</view>
              </view>
              <view class="stat-item">
                <view class="stat-value">{{ participantCount }}</view>
                <view class="stat-label">参与选手</view>
              </view>
              <view class="stat-item">
                <view class="stat-value">{{ voterCount }}</view>
                <view class="stat-label">投票人数</view>
              </view>
              <view class="stat-item">
                <view class="stat-value">{{ remainingVotes }}</view>
                <view class="stat-label">剩余票数</view>
              </view>
            </view>
          </view>
          
          <view class="grade-filter">
            <button 
              v-for="(grade, index) in gradeLists" 
              :key="index"
              @click="handleGradeButtonClick(index)"
              :class="{ 
                active: activeGradeIndex === index,
                disabled: isGradeButtonDisabled(index)
              }"
            >
              {{ grade.title }}
            </button>
          </view>

          <!-- 只显示当前选中的年级项目 -->
          <view class="grade-section">
            <view class="grade-title">{{ currentGrade.title }}</view>
            <view class="grade-subtitle">共 {{ currentGrade.list.length }} 个项目</view>
            
            <ParticipantList
              :participants="currentGrade.list" 
              :sortBy="sortBy"
              :isVotingEnded="isVotingEnded"
              :loading="loading || isVotingProcessing"
              :remainingVotes="remainingVotes"
              @handleVote="handleVote"
              @loadMore="loadMore"
            />
          </view>
          <!-- 投票结束遮罩 -->
          <view class="vote-ended-overlay" v-show="isVotingEnded">
            <view class="overlay-content">
              <text class="fa fa-check-circle fa-3x mb-2"></text>
              <view class="overlay-title">投票已结束</view>
              <view class="overlay-desc">感谢您的参与</view>
            </view>
          </view>
          
          <!-- 加载中遮罩 -->
          <view class="loading-overlay" v-show="loading || isVotingProcessing">
            <view class="loading-content">
              <text class="fa fa-spinner fa-spin fa-2x mb-2"></text>
              <view class="loading-text">{{ loading ? '加载中...' : '处理中...' }}</view>
            </view>
          </view>
          <!-- 剩余票数用完弹框 -->
          <view class="ticket-used-up-modal" v-show="isTicketUsedUp">
            <view class="modal-mask" @click="closeTicketModal"></view>
            <view class="modal-content">
              <view class="modal-header">
                <text class="modal-title">票数已用完</text>
              </view>
              <view class="modal-body">
                <text class="modal-desc">您的剩余票数已用完，无法继续投票</text>
              </view>
              <view class="modal-footer">
                <button class="close-btn" @click="closeTicketModal">确定</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="drawer-mask" :class="{ 'drawer-mask-show': isDrawerOpen }" @click="toggleDrawer"></view>
    
    <!-- 禁用按钮提示弹框 -->
    <view class="disabled-button-modal" v-if="showDisabledButtonModal">
      <view class="modal-mask" @click="closeDisabledButtonModal"></view>
      <view class="modal-content">
        <view class="modal-title">提示</view>
        <view class="modal-message">当前页面只展示正在投票项目</view>
        <button class="modal-confirm" @click="closeDisabledButtonModal">我知道了</button>
      </view>
    </view>
  </view>
</template>

<script>
// 引入 DanmuChat 组件
import DanmuChat from '@/component/DanmuChat.vue';
import TopTimerAndCountdown from '@/component/TopTimerAndCountdown.vue';
import ParticipantList from '@/component/ParticipantList.vue';
import { get, deleteCountdown } from '@/api/countdown.js'; // 引入获取倒计时的接口
import { getAllProject, voteProject, cancelVoteProject, getRemainingVotes, setRemainingVotes, getVoteId } from '@/api/details.js';

export default {
  name: 'DouyinLive',
  components: {
    DanmuChat, // 注册 DanmuChat 组件
    TopTimerAndCountdown,
    ParticipantList
  },
  data() {
    return {
		pollingTimer: null,
		      anotherTimer: null,
		      isActive: true,
		      webSocket: null,
      liveUrl: '/live/xgdzhibo/zhibojian.m3u8?auth_key=1750404167-0-0-3669c0ac8d055dae83ee23ab84566fb7',
      isLiking: false,
      activeLikes: [],
      subscribeTopic: "/game/message",
      sendTopic: "/mori/message",
      boxWidth: 220,
      boxHeight: 260,
      massage: [],
      boxBackgroundColor: 'rgba(0, 0, 0, 0.5)',
      isDrawerOpen: false,
      // 新增：模拟商品数据
      gradeLists: [
        { 
          title: '大一项目', 
          list: [],
          voteId: '1'  // 改为字符串，因为从API获取的数据可能是字符串
        },
        { 
          title: '大二项目', 
          list: [],
          voteId: '2'  // 改为字符串
        },
        { 
          title: '大三项目', 
          list: [],
          voteId: '3'  // 改为字符串
        }
      ],
      activeGradeIndex: 0, // 当前选中的年级索引
      // 计时器数据
      timer: { days: 0, hours: 0, minutes: 0, seconds: 0 },
      countdown: { days: 0, hours: 0, minutes: 10, seconds: 0 },
      
      // 统计数据
      totalVotes: 0,
      participantCount: 0,
      voterCount: 0,
      remainingVotes: 0,
      
      // 排序和加载状态
      sortBy: 'votes',
      loading: false,
      isVotingProcessing: false,
      
      // 数据列表
      participants: [],
      pageSize: 6,
      currentPage: 1,
      
      // 提示消息
      showToast: false,
      toastType: 'success',
      toastMessage: '',
      
      // 投票状态
      isVotingEnded: false,
      
      // WebSocket
      socketTask: null,
      webSocketConnected: false,
      webSocketErrorCount: 0,
      
      // 定时器
      timerInterval: null,
      countdownInterval: null,
      timer2: null,
      isActive:true,
      // 票数用完弹框状态
      isTicketUsedUp: false,
      voteId: null, // 初始化为null，等待API获取
      isLoading: true, // 新增加载状态
      showDisabledButtonModal: false, // 新增：禁用按钮提示弹框状态
    }
  },
  computed: {
    // 当前选中的年级
    currentGrade() {
      return this.gradeLists[this.activeGradeIndex] || this.gradeLists[0];
    },
    // 判断按钮是否应该显示为禁用状态
    isGradeButtonDisabled() {
      return (index) => {
        // 增加对voteId的空值检查
        if (!this.voteId) return true;
        
        // 使用宽松比较，不强制转换类型
        return this.voteId != this.gradeLists[index].voteId;
      }
    }
  },
  created() {
    this.startCountdownLoop(); // 启动循环

    // 获取投票ID并初始化页面
    this.initializeVoteId();
  },
  
  onShow() {
      // 页面显示时恢复轮询
      this.isActive = true;
      this.startPolling();
    },
    
    onHide() {
      // 页面隐藏时停止轮询
      this.isActive = false;
      this.stopPolling();
    },
  onLoad() {
    // 页面加载时开始轮询
    this.startPolling();
    
    // 监听全局事件
    uni.$on('stopPolling', this.stopPolling);
  },
  
  onUnload() {
    // 页面卸载时清理资源
    this.cleanupResources();
  },
  
  activated() {
    // 被keep-alive缓存的组件激活时
    this.isActive = true;
    this.startPolling();
  },
  
  deactivated() {
    // 被keep-alive缓存的组件停用时
    this.isActive = false;
    this.stopPolling();
  },
  
  beforeDestroy() {
    this.cleanupResources();
  },
  
  beforeUnmount() {
    this.cleanupResources();
  },
  
  mounted() {
    // 从本地存储获取voteId
    const storedVoteId = uni.getStorageSync('voteId');
    if (storedVoteId && storedVoteId.data) {
      this.voteId = storedVoteId.data;
      console.log('从本地存储获取voteId:', this.voteId);
    }
    
    // 初始化其他资源
    this.initPlayer();
    this.initWebSocket();
    this.startCountdown();
    this.startTimer();
    this.aaa();
    this.fetchData1();
    
    // 使用单独的定时器变量
    this.pollingTimer = setInterval(() => {
      if (this.isActive) this.fetchData1();
    }, 5000);
    
    this.anotherTimer = setInterval(() => {
      if (this.isActive) this.fetchData1();
    }, 3000);
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
    
    // 监听浏览器返回/刷新
    window.addEventListener('beforeunload', this.cleanupResources);
  },
  
  methods: {
	  // 添加退出直播间方法
	      exitLiveRoom() {
	        // 使用uni-app的导航API跳转到指定页面
	        uni.switchTab({
	          url: '/pages/index/index'
	        });
	      },
    startPolling() {
      if (!this.pollingTimer && this.isActive) {
        this.fetchData1();
        this.pollingTimer = setInterval(() => {
          this.fetchData1();
        }, 5000);
      }
    },
    
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
      
      if (this.anotherTimer) {
        clearInterval(this.anotherTimer);
        this.anotherTimer = null;
      }
    },
    
    handleVisibilityChange() {
      if (document.hidden) {
        this.isActive = false;
        this.stopPolling();
      } else {
        this.isActive = true;
        this.startPolling();
      }
    },
    
    cleanupResources() {
      this.isActive = false;
      this.stopPolling();
      
      // 移除所有事件监听
      document.removeEventListener('visibilitychange', this.handleVisibilityChange);
      window.removeEventListener('beforeunload', this.cleanupResources);
      uni.$off('stopPolling', this.stopPolling);
      
      // 关闭WebSocket
      if (this.webSocket) {
        this.webSocket.close();
        this.webSocket = null;
      }
    },
    
    fetchData1() {
      if (!this.isActive) return;
      
      this.aaa();
      this.initializeVoteId();
    },

    // 初始化投票ID
    initializeVoteId() {
      getVoteId().then((data) => {
        if (data && data.code === 200 && data.data) {
          uni.setStorageSync('voteId', data);
          this.voteId = data.data; // 提取实际的投票ID值
          console.log('从服务器获取voteId:', this.voteId);
          
          // 选择第一个可用的年级按钮
          this.selectFirstEnabledGradeButton();
          
          // 获取剩余票数
          this.getRemainingVotes();
          
          // 加载数据
          this.fetchData();
        } else {
          console.error('获取的voteId为空或格式不正确:', data);
          // 处理获取失败的情况，可以使用本地存储的旧值或显示错误提示
          this.showToastMessage('error', '获取投票信息失败，请刷新页面');
        }
        
        // 完成加载
        this.isLoading = false;
      }).catch(error => {
        console.error('获取voteId失败:', error);
        this.showToastMessage('error', '网络错误，请刷新页面');
        this.isLoading = false;
      });
    },
    
    // 选择第一个未被禁用的年级按钮
    selectFirstEnabledGradeButton() {
      console.log('尝试选择第一个可用的年级按钮，当前voteId:', this.voteId);
      
      // 如果voteId还未获取到，不执行选择逻辑
      if (!this.voteId) {
        console.log('voteId为空，不执行选择逻辑');
        return;
      }
      
      for (let i = 0; i < this.gradeLists.length; i++) {
        const isDisabled = this.isGradeButtonDisabled(i);
        console.log(`年级按钮 ${i} (${this.gradeLists[i].title}) 是否禁用:`, isDisabled);
        
        if (!isDisabled) {
          console.log(`选择年级按钮 ${i} (${this.gradeLists[i].title})`);
          this.activeGradeIndex = i;
          this.aaa();
          break;
        }
      }
    },
    
    // 处理年级按钮点击
    handleGradeButtonClick(index) {
      // 调试输出，检查按钮状态和点击事件
      console.log(`点击年级按钮 ${index} (${this.gradeLists[index].title})`);
      console.log(`按钮是否应该禁用: ${this.isGradeButtonDisabled(index)}`);
      
      // 如果按钮应该被禁用，显示提示
      if (this.isGradeButtonDisabled(index)) {
        console.log('显示禁用按钮提示弹框');
        this.showDisabledButtonModal = true;
        return;
      }
      
      // 正常处理按钮点击
      this.activeGradeIndex = index;
      this.aaa();
    },
    
    // 关闭禁用按钮提示弹框
    closeDisabledButtonModal() {
      console.log('关闭禁用按钮提示弹框');
      this.showDisabledButtonModal = false;
    },
    
    aaa() {
      console.log('ssfs');
      setRemainingVotes().then((data) => {
        
      });
      this.getRemainingVotes();
    },
    
    // 启动倒计时循环
    startCountdownLoop() {
      this.countdownInterval = setInterval(async () => {
        await this.updateCountdown();
      }, 1000); // 每秒执行一次
    },
    
    // 更新倒计时的方法
    async updateCountdown() {
      try {
        const response = await get();
        if(response){
          let newCountdown = {
            days: response.days,
            hours: response.hours,
            minutes: response.minutes,
            seconds: response.seconds
          };
          console.log(newCountdown);
          this.handUpdateCountdown(newCountdown);
          await deleteCountdown();
        }
      } catch (error) {
        console.error('更新倒计时失败:', error);
      }
    },
    
    // 处理倒计时结束事件
    handleCountdownEnded() {
      this.isVotingEnded = true;
      this.showToastMessage('info', '投票已结束，感谢参与');
    },
    
    // 处理倒计时重新开始事件
    handleCountdownRestart() {
      this.isVotingEnded = false;
    },
    
    handUpdateCountdown(newCountdown){
      console.log(newCountdown,111);
      this.$refs.topTimerAndCountdown.handleStartManualCountdown(newCountdown);
    },
    
    videoErrorCallback(error) {
      console.error('视频播放错误:', error);
      uni.showToast({
        title: '视频播放出错',
        icon: 'none'
      });
    },
    
    //初始化直播
    initPlayer() {
      // 确保第三方播放器库已加载
      if (typeof Hls !== 'undefined') {
        const videoContainer = document.getElementById('videoContainer');
        
        if (videoContainer) {
          
          // 创建video元素
          const videoElement = document.createElement('video');
          videoElement.id = 'livePlayer';
          videoElement.className = 'live-player';
          videoElement.autoplay = true;
          videoElement.controls = true;
          videoElement.style.width = '100%';
          videoElement.style.height = '100%';
              
          videoContainer.appendChild(videoElement);
          
          // 初始化HLS播放器
          if (Hls.isSupported()) {
            
            this.player = new Hls();
            this.player.loadSource(this.liveUrl);
            this.player.attachMedia(videoElement);
            this.player.on(Hls.Events.MANIFEST_PARSED, () => {
              console.log('HLS播放器初始化成功');
            });
            this.player.on(Hls.Events.ERROR, (event, data) => {
              console.error('HLS播放器错误:', data);
              this.videoErrorCallback(data);
            });
          } 
          // 浏览器原生支持HLS
          else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
            
            videoElement.src = this.liveUrl;
            videoElement.addEventListener('loadedmetadata', () => {
              videoElement.play();
            });
            videoElement.addEventListener('error', (e) => {
              this.videoErrorCallback(e);
            });
          } else {
            console.error('当前浏览器不支持HLS播放');
            uni.showToast({
              title: '当前浏览器不支持直播播放',
              icon: 'none'
            });
          }
        }
      } else {
        console.error('HLS库未加载，请确保在index.html中引入了HLS.js');
        uni.showToast({
          title: '直播播放器加载失败',
          icon: 'none'
        });
      }
    },
    
    handleLike() {
      this.isLiking = true;
      
      // 添加点赞动画
      for (let i = 0; i < 5; i++) {
        setTimeout(() => {
          this.addLikeAnimation();
        }, i * 100);
      }
      
      // 重置点赞状态
      setTimeout(() => {
        this.isLiking = false;
      }, 500);
    },
    
    addLikeAnimation() {
      const left = 20 + Math.random() * 60;
      const animation = {
        style: {
          left: `${left}%`,
          animation: `likeFloat ${1 + Math.random() * 2}s ease-in forwards`
        }
      };
      
      this.activeLikes.push(animation);
      
      // 移除动画
      setTimeout(() => {
        this.activeLikes.shift();
      }, 2000);
    },
    
    toggleDrawer() {
      this.isDrawerOpen = !this.isDrawerOpen;
    },
    
    // 获取数据
    async fetchData() {
      this.loading = true;
      
      try {
        const response = await getAllProject();
        this.participants = response.data || [];
        console.log('获取到的项目数据:', this.participants);
        
        // 确保每个项目都有voteStatus字段
        this.participants.forEach(project => {
          if (!project.hasOwnProperty('voteStatus')) {
            project.voteStatus = 'default';
          }
        });
        
        this.participantCount = this.participants.length;
        this.totalVotes = this.participants.reduce(
          (sum, p) => sum + (p.totalVotes || 0) + (p.totalInsideVotes || 0), 0
        );
        
        // 按年级分类项目
        this.classifyParticipantsByGrade();
        
        // 重新计算投票百分比
        this.recalculateVotePercentages();
      } catch (error) {
        console.error('获取数据失败:', error);
        this.showToastMessage('error', '获取数据失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    
    // 按年级分类项目
    classifyParticipantsByGrade() {
      // 先清空年级列表
      this.gradeLists.forEach(grade => {
        grade.list = [];
      });
      
      // 遍历所有项目并分类
      this.participants.forEach(project => {
        // 确保project对象存在voteId属性
        if (project.voteId) {
          const grade = this.gradeLists.find(g => g.voteId === project.voteId);
          if (grade) {
            grade.list.push(project);
          }
        } else {
          console.warn('项目缺少voteId属性:', project);
        }
      });
      
      console.log('分类后的年级数据:', this.gradeLists);
    },
    
    // 重新计算投票百分比（每个年级内独立计算）
    recalculateVotePercentages() {
      this.gradeLists.forEach(grade => {
        // 计算该年级的总票数
        const totalVotes = grade.list.reduce(
          (sum, p) => sum + (p.totalVotes || 0) + (p.totalInsideVotes || 0), 0
        );
        
        // 计算每个项目的百分比
        grade.list.forEach(p => {
          const projectVotes = (p.totalVotes || 0) + (p.totalInsideVotes || 0);
          p.votePercent = totalVotes > 0 ? 
            ((projectVotes / totalVotes) * 100).toFixed(1) : '0.0';
        });
      });
    },

    // 初始化WebSocket
    initWebSocket() {
      // 从本地存储获取用户ID
      const userInfo = uni.getStorageSync('userInfo');
      const userId = userInfo?.id;
      
      if (!userId) {
        console.error('未获取到用户ID，无法建立WebSocket连接');
        return;
      }
      
      // 建立WebSocket连接
      this.socketTask = uni.connectSocket({
        url: `ws://localhost:8080/ws/vote?userId=${userId}`,
        success: () => {
          console.log('WebSocket连接请求已发送，用户ID:', userId);
          this.webSocketConnected = true;
          this.webSocketErrorCount = 0;
        },
        fail: (err) => {
          console.error('WebSocket连接失败:', err);
          this.showToastMessage('error', 'WebSocket连接失败，请稍后重试');
        }
      });
      
      // 监听连接打开事件
      this.socketTask.onOpen(() => {
        console.log('WebSocket连接已建立，用户ID:', userId);
        this.webSocketConnected = true;
        this.webSocketErrorCount = 0;
      });
      
      // 监听消息事件
      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data);
          console.log('收到WebSocket消息:', data);
          
          // 处理不同类型的消息
          if (data.type === 'remainingVotes') {
            // 剩余票数更新
            this.updateRemainingVotes(data.remainingVotes);
            this.showToastMessage('success', '剩余票数已更新');
          } else if (data.type === 'projectVotes') {
            // 项目票数更新
            this.updateProjectVotes(data.projects);
          } else {
            console.log('未知类型的WebSocket消息:', data);
          }
        } catch (e) {
          console.error('解析WebSocket消息失败:', e);
        }
      });
      
      // 监听连接关闭事件
      this.socketTask.onClose((event) => {
        console.log('WebSocket连接已关闭，代码:', event.code, '原因:', event.reason);
        this.webSocketConnected = false;
        
        // 自动重连（最多5次）
        if (this.webSocketErrorCount < 5) {
          setTimeout(() => {
            this.webSocketErrorCount++;
            console.log(`尝试重新连接WebSocket (${this.webSocketErrorCount}/5)`);
            this.initWebSocket();
          }, 3000);
        } else {
          this.showToastMessage('warning', 'WebSocket连接失败，请刷新页面');
        }
      });
      
      // 监听连接错误事件
      this.socketTask.onError((err) => {
        console.error('WebSocket错误:', err);
        this.webSocketConnected = false;
        this.showToastMessage('error', 'WebSocket连接错误，请稍后重试');
      });
    },
    
    // 获取用户剩余票数
    async getRemainingVotes() {
      try {
        const response = await getRemainingVotes();
        if (response.code === 200) {
          this.remainingVotes = response.data;
          this.checkRemainingVotes(); // 检查是否需要显示弹框
        } else {
          console.error('获取剩余票数失败:', response.msg);
          this.showToastMessage('error', '获取剩余票数失败，请稍后重试');
        }
      } catch (error) {
        console.error('获取剩余票数失败:', error);
        this.showToastMessage('error', '获取剩余票数失败，请稍后重试');
      }
    },

    // 投票处理
    async handleVote(item) {
      if (this.isVotingEnded || this.isVotingProcessing) {
        this.showToastMessage('info', this.isVotingEnded ? '投票已结束' : '操作处理中...');
        return;
      }
      
      // 检查剩余票数
      if (this.remainingVotes <= 0) {
        this.isTicketUsedUp = true;
        return;
      }
      
      this.isVotingProcessing = true;
      
      try {
        const isVoting = item.voteStatus === 'default';
        const method = isVoting ? voteProject : cancelVoteProject;
        const response = await method({ projectId: item.projectId });
        
        if (response.code === 200) {
          console.log(isVoting ? '投票成功' : '取消投票成功');
          this.showToastMessage('success', isVoting ? '投票成功' : '取消投票成功');
        } else {
          this.showToastMessage('error', response.msg || '操作失败');
        }
      } catch (error) {
        console.error('投票请求失败:', error);
        this.showToastMessage('error', '网络错误，请稍后重试');
      } finally {
        this.isVotingProcessing = false;
      }
    },
    
    // 更新项目票数
    updateProjectVotes(projects) {
      if (!projects || !projects.length) return;
      
      // 更新本地项目列表中的票数
      projects.forEach(updatedProject => {
        const index = this.participants.findIndex(p => p.projectId === updatedProject.projectId);
        if (index !== -1) {
          this.participants[index] = {
            ...this.participants[index],
            totalVotes: updatedProject.totalVotes,
            totalInsideVotes: updatedProject.totalInsideVotes
          };
        }
      });
      
      // 重新计算总票数和百分比
      this.totalVotes = this.participants.reduce(
        (sum, p) => sum + (p.totalVotes || 0) + (p.totalInsideVotes || 0), 0
      );
      this.classifyParticipantsByGrade();
      this.recalculateVotePercentages();
      
      // 显示更新提示
      this.showToastMessage('success', '投票数据已更新');
    },
    
    // 更新剩余票数
    updateRemainingVotes(remainingVotes) {
      this.remainingVotes = remainingVotes;
      this.checkRemainingVotes();
    },
    
    // 检查剩余票数并显示弹框
    checkRemainingVotes() {
      if (this.remainingVotes <= 0 && !this.isTicketUsedUp) {
        this.isTicketUsedUp = true;
      }
    },
    
    // 关闭票数用完弹框
    closeTicketModal() {
      this.isTicketUsedUp = false;
    },
    
    // 显示提示消息
    showToastMessage(type, message) {
      this.toastType = type;
      this.toastMessage = message;
      this.showToast = true;
      setTimeout(() => {
        this.showToast = false;
      }, 3000);
    },
    
    // 加载更多
    loadMore() {
      // 加载更多逻辑
    },
    
    // 倒计时逻辑
    startCountdown() {
      // 倒计时逻辑
    },
    
    // 计时器逻辑
    startTimer() {
      // 计时器逻辑
    }
  },
  onUnload() {
    // 清理资源，关闭 WebSocket 连接和定时器
    if (this.socketTask) {
      this.socketTask.close();
    }
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
    if (this.timer2) {
      clearInterval(this.timer2);
    }
  }
}
</script>







<style lang="scss" >
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
// 添加以下样式
.grade-filter button.disabled {
  background-color: #e0e0e0;
  color: #999;
  cursor: not-allowed;
  opacity: 0.7;
  /* 移除 pointer-events: none，让点击事件能够触发 */
}

// 新增弹框样式
.disabled-button-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  
  .modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    max-width: 300px;
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    
    .modal-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }
    
    .modal-message {
      font-size: 16px;
      color: #666;
      margin-bottom: 20px;
    }
    
    .modal-confirm {
      width: 100%;
      height: 40px;
      background-color: #007AFF;
      color: #fff;
      border-radius: 8px;
      font-size: 16px;
      line-height: 40px;
    }
  }
}


// 新增弹框样式
.disabled-button-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  
  .modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    max-width: 300px;
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    
    .modal-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }
    
    .modal-message {
      font-size: 16px;
      color: #666;
      margin-bottom: 20px;
    }
    
    .modal-confirm {
      width: 100%;
      height: 40px;
      background-color: #007AFF;
      color: #fff;
      border-radius: 8px;
      font-size: 16px;
      line-height: 40px;
    }
  }
}

/* 票数用完弹框样式 */
.ticket-used-up-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background-color: #fff;
  border-radius: 12px;
  width: 80%;
  max-width: 400px;
  padding: 30px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  text-align: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.modal-body {
  text-align: center;
  margin-bottom: 20px;
}

.modal-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.modal-footer {
  display: flex;
  justify-content: center;
}

.close-btn {
  background-color: #f56c6c;
  color: #fff;
  padding: 10px 30px;
  border-radius: 20px;
  font-size: 14px;
}
.search-and-stats{
	padding: 0 16px 16px;
	background-color: #fff;
	margin-bottom: 12px;
}
.stats {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-top: 1px solid #eee;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
  color: #ff3b30;
}

.stat-label {
  font-size: 12px;
  color: #666;
}
page {
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background: #000;
  color: #fff;
  overflow: hidden;
  touch-action: manipulation;
}

.live-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 直播视频区域 */
.live-video {
  position: absolute;
  top: 20vh;
  left: 0;
  width: 100%;
  height: 50vh;
  z-index: 1;
  
  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
    z-index: 2;
  }
}

/* 顶部主播信息 */
.live-header {
  position: absolute;
  top: 12px;
  left: 0;
  width: 100%;
  padding: 0 16px;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .host-info {
    display: flex;
    align-items: center;
    
    .host-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      border: 2px solid #ff3b77;
      overflow: hidden;
      margin-right: 12px;
      
      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .host-details {
      .host-name {
        font-size: 16px;
        font-weight: 700;
        margin-bottom: 4px;
      }
      
      .live-status {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.9);
        
        .live-indicator {
          width: 8px;
          height: 8px;
          background: #ff3b77;
          border-radius: 50%;
          margin-right: 6px;
          animation: pulse 1.5s infinite;
        }
      }
    }
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    
    .follow-btn {
      background: linear-gradient(to right, #ff3b77, #ff6b9c);
      color: white;
      border: none;
      padding: 6px 18px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: bold;
      margin-right: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }
    
    .menu-btn {
      background: rgba(0, 0, 0, 0.4);
      color: white;
      border: none;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 16px;
    }
  }
}

/* 弹幕聊天区域 */
.chat-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
}

.live-player{
  width: 100%;
  height: 100%;
  z-index: 999;
}

/* 点赞动画 */
.like-animations {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 20;
  
  .like-animation {
    position: absolute;
    bottom: 120px;
    font-size: 28px;
    color: #ff3b77;
    opacity: 0;
    animation: likeFloat 1.5s ease-in forwards;
  }
}

/* 动画定义 */
@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

@keyframes likeFloat {
  0% {
    opacity: 1;
    transform: translateY(0) scale(0.8);
  }
  50% {
    opacity: 0.8;
    transform: translateY(-100px) scale(1.2);
  }
  100% {
    opacity: 0;
    transform: translateY(-200px) scale(1.5);
  }
}

/* 适配不同屏幕尺寸 */
@media (max-height: 700px) {
  .chat-panel {
    padding-bottom: 20px;
  }
  .message-input-text {
    height: 5vh; // 调整小屏幕下的高度
  }
}
.grade-section {
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.grade-title {
  padding: 12px 16px;
  font-size: 18px;
  font-weight: bold;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.grade-subtitle {
  padding: 8px 16px;
  font-size: 14px;
  color: #666;
  background-color: #f9f9f9;
}
/* 年级筛选按钮 */
.grade-filter {
  display: flex;
  justify-content: center;
  padding: 10px 0;
  background-color: white;
  margin-bottom: 10px;
}

.grade-filter button {
  flex: 1;
  margin: 0 5px;
  padding: 8px 0;
  background-color: #f5f5f5;
  border-radius: 5px;
  font-size: 14px;
  color: #666;
  border: none;
  transition: all 0.3s;
}

.grade-filter button.active {
  background-color: #f56c6c;
  color: white;
}

/* 抽屉样式 */
.drawer {
  position: fixed;
  top: 0;
  right: -100%;
  width: 100%;
  height: 100%;
  background-color: #fff;
  z-index: 100;
  transform: scale(0.9) translateX(10%);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
}

.drawer-open {
  @media (min-width: 768px) {
    right: 0;
    width: 30%;
    transform: scale(1) translateX(0);
    opacity: 1;
  }
  @media (max-width: 767px) {
    right: 0;
    width: 90%;
    transform: scale(1) translateX(0);
    opacity: 1;
  }
  overflow: hidden; /* 确保抽屉容器不显示滚动条 */
}

/* 抽屉内容容器样式 */
.drawer-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow-y: auto; /* 垂直方向自动显示滚动条 */
  -webkit-overflow-scrolling: touch; /* 优化移动端滚动体验 */
  color: #333;
}

/* 抽屉头部样式 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 15px;
  color: #ff8f8f;
  position: relative;
  left: 100px;
  cursor: pointer;
}

/* 主播信息样式 */
.anchor-info {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.anchor-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
}

.anchor-avatar image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.anchor-details {
  flex: 1;
}

.anchor-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.anchor-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.anchor-stats {
  display: flex;
}

.stat-item {
  margin-right: 15px;
}

.stat-value {
  font-size: 14px;
  font-weight: bold;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

/* 直播信息样式 */
.live-details {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.live-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.live-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.tag {
  background-color: #f0f0f0;
  color: #666;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.live-meta {
  display: flex;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.meta-item text:first-child {
  margin-right: 5px;
}

/* 商品列表样式 */
.live-products {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.product-item {
  display: flex;
  margin-bottom: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
}

.product-image image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff3b77;
}

.buy-btn {
  background-color: #ff3b77;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 14px;
  width: fit-content;
}

/* 测试内容样式 */
.test-content {
  padding: 20px;
}

.test-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #666;
}

/* 抽屉底部样式 */
.drawer-footer {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.share-btn, .report-btn {
  background: none;
  border: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.share-btn text:first-child, .report-btn text:first-child {
  font-size: 20px;
  margin-bottom: 5px;
}

/* 抽屉遮罩层样式 */
.drawer-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 99;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s cubic-bezier(0.25, 0.8, 0.25, 1), visibility 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.drawer-mask-show {
  opacity: 1;
  visibility: visible;
}

/* 自定义滚动条样式 */
.drawer-content::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}

.drawer-content::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道背景 */
}

.drawer-content::-webkit-scrollbar-thumb {
  background: #c1c1c1; /* 滚动条滑块背景 */
  border-radius: 3px;
}

.drawer-content::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1; /* 鼠标悬停时的滑块背景 */
}
</style>